{{define "es2index"}}
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>{{.Title}}</title>
		<link
			href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css"
			rel="stylesheet"
		/>
		<link
			href="https://cdn.datatables.net/v/bs5/jq-3.7.0/jszip-3.10.1/dt-2.0.2/b-3.0.1/b-html5-3.0.1/b-print-3.0.1/r-3.0.0/rg-1.5.0/sc-2.4.1/datatables.min.css"
			rel="stylesheet"
		/>
		<style>
			tr.group,
			tr.group:hover {
				background-color: rgba(0, 0, 0, 0.1) !important;
				text-align: right;
			}

			:root.dark tr.group,
			:root.dark tr.group:hover {
				background-color: rgba(0, 0, 0, 0.75) !important;
				text-align: right;
			}
			.alerts {
				max-height: 57px;
				overflow: hidden;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<h1 class="otchet_name"></h1>
			<div class="alerts"></div>
			<table id="es2pdcotchet" class="table table-striped table-hover"></table>
		</div>
	</body>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
	<script src="https://cdn.datatables.net/v/bs5/jq-3.7.0/jszip-3.10.1/dt-2.0.2/b-3.0.1/b-html5-3.0.1/b-print-3.0.1/r-3.0.0/rg-1.5.0/sc-2.4.1/datatables.min.js"></script>
	<script>
		let addAlert = (msg, cls='primary') => {
			let alertHTML = `<div id="report-alert" class="alert alert-${cls} alert-dismissible fade show" role="alert">
				<span class="msg">${msg}</span>
				<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
			  </div>`;
			$(".alerts").append(alertHTML);
			let alert = bootstrap.Alert.getOrCreateInstance("#report-alert");
			return alert;
		};
		let parseTime = (dateString) => {
			const date = new Date(dateString);
			const day = date.getDate().toString().padStart(2, "0");
			const month = (date.getMonth() + 1).toString().padStart(2, "0");
			const year = date.getFullYear();
			const hours = date.getHours().toString().padStart(2, "0");
			const minutes = date.getMinutes().toString().padStart(2, "0");

			const newDateString = `${day}-${month}-${year} | ${hours}:${minutes}`;
			return newDateString;
		};
		async function main() {
			let loadingButton = document.createElement("Button");
			loadingButton.classList = "btn btn-primary loading-butt";
			$(loadingButton).attr({ type: "button", disabled: "true", hidden: "true" });
			loadingButton.innerHTML = `	<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
  										<span class="visually-hidden">Loading...</span>`;
			let groupColumn = 0;
			let table = new DataTable("#es2pdcotchet", {
				title: "TableName",
				columnDefs: [{ visible: false, targets: groupColumn }],
				responsive: true,
				pageLength: 15,
				layout: {
					topStart: {
						pageLength: {
							menu: [15, 25, 50, { label: "All", value: -1 }],
						},
						buttons: [
							{
								extend: "pdfHtml5",
								text: "Экспорт в PDF",
								exportOptions: {
									modifier: {
										page: "current",
									},
								},
							},
							"excelHtml5",
							{
								text: "Обновить данные",
								name: "data_update",
								action: function (e, dt, node, config) {
									if (location.host === "es2pdcotchet.uooio.keenetic.pro") $('button:contains("Обновить данные")').hide();
									this.disable();
									let butpan = document.querySelector(".dt-buttons");
									if (butpan.querySelector(".loading-butt")) {
									} else {
										butpan.insertAdjacentElement("beforeend", loadingButton);
									}
									node[0].hidden = true;
									loadingButton.hidden = false;
									let url = dt.ajax.url();
									let nURL = url.includes("?force_update") ? url : url + "?force_update";
									dt.on("xhr.dt", (e, settings, json, xhr) => {
										let a = bootstrap.Alert.getOrCreateInstance("#report-alert");
										Object.keys(a).length ? a.close() : a = null;
										loadingButton.hidden = true;
										node[0].hidden = false;
										this.enable();
										if (!json) {
											addAlert("Не удалось загрузить отчет.", "danger");
											if (location.host === "es2pdcotchet.uooio.keenetic.pro") $('button:contains("Обновить данные")').hide();
											return;
										}
										addAlert("Данные успешно обновлены.", "success");
										if (location.host === "es2pdcotchet.uooio.keenetic.pro") $('button:contains("Обновить данные")').hide();
									});
									dt.ajax.url(nURL).load();
								},
							},
						],
					},
				},
				ajax: {
					url: "{{js .Api}}" + "{{js .OtchetPDCURLGet}}",
					dataSrc: function (json) {
						if (json.status === "fail") {
							addAlert(`Не удалось загрузить отчет. [${json.message}]`);
							return;
						}
						let tableData = [];
						for (let s of json.otchet.schools) {
							for (let p of s.parents) {
								let errors = p.childs[0].valid_res.concat(p.valid_res).join("<br>");
								tableData.push({
									school: s.name,
									c_cid: p.childs[0].npc,
									c_name: p.childs[0].name,
									errors: errors,
								});
							}
						}
						document.querySelector(".otchet_name").innerHTML = `${
							json.otchet.name
						}  <span class="badge bg-primary">${parseTime(json.otchet.UpdatedAt)}</span>`;
						document.title = `Отчеты: ЭШ 2.0[Общие сведения об обучающихся] - [${parseTime(
							json.otchet.UpdatedAt
						)}]`;
						if (json.state == "outdated")  {
							table.button("data_update:name").trigger();
						}
						
						return tableData;
					},
				},
				columnDefs: [{ visible: false, targets: groupColumn }],
				order: [[groupColumn, "asc"]],
				drawCallback: function (settings) {
					var api = this.api();
					var rows = api.rows({ page: "current" }).nodes();
					var last = null;

					api
						.column(groupColumn, { page: "current" })
						.data()
						.each(function (group, i) {
							if (last !== group) {
								$(rows)
									.eq(i)
									.before('<tr class="group"><td colspan="5">' + group + "</td></tr>");
								last = group;
							}
						});
				},
				columns: [
					{ title: "Школа", data: "school" },
					{ title: "№ личного дела", data: "c_cid" },
					{ title: "Обучающийся", data: "c_name" },
					{ title: "Ошибки", data: "errors" },
				],
			});
			if (location.host === "es2pdcotchet.uooio.keenetic.pro") $('button:contains("Обновить данные")').hide();
		}
		main();
	</script>
</html>
{{end}}
